/**
 * @file system.c
 * @brief 系统管理模块实现
 */

#include "action_camera.h"

/**
 * @brief 系统初始化
 * @return 0成功，-1失败
 */
int system_init(void) {
    memset(&g_camera_system, 0, sizeof(action_camera_system_t));
    
    // 初始化系统状态
    g_camera_system.state = SYSTEM_INIT;
    g_camera_system.start_time = get_system_timestamp();
    
    // 初始化同步对象
    pthread_mutex_init(&g_camera_system.sync.config_mutex, NULL);
    pthread_mutex_init(&g_camera_system.sync.stats_mutex, NULL);
    pthread_mutex_init(&g_camera_system.sync.log_mutex, NULL);
    pthread_cond_init(&g_camera_system.sync.shutdown_cond, NULL);
    
    atomic_init(&g_camera_system.sync.system_running, true);
    atomic_init(&g_camera_system.sync.active_threads, 0);
    atomic_init(&g_camera_system.sync.system_timestamp, 0);
    
    // 设置默认配置
    g_camera_system.config.video_format = VIDEO_FORMAT_1080P_30FPS;
    g_camera_system.config.video_bitrate = 8000000; // 8Mbps
    g_camera_system.config.audio_sample_rate = 48000;
    g_camera_system.config.audio_enabled = true;
    g_camera_system.config.wifi_enabled = false;
    g_camera_system.config.auto_record = false;
    g_camera_system.config.max_file_size_mb = 4000; // 4GB
    strcpy(g_camera_system.config.storage_path, "/mnt/sdcard/");
    
    // 初始化线程监控信息
    const char* thread_names[] = {
        "Main", "Camera", "Encoder", "Audio", 
        "Storage", "UI", "Monitor", "Network"
    };
    
    for (int i = 0; i < MAX_THREADS; i++) {
        g_camera_system.threads[i].status = THREAD_INIT;
        g_camera_system.threads[i].error_count = 0;
        strcpy(g_camera_system.threads[i].thread_name, thread_names[i]);
        g_camera_system.threads[i].enabled = (i == THREAD_MAIN) ? false : true;
    }
    
    // 初始化消息队列
    for (int i = 0; i < MAX_THREADS; i++) {
        if (message_queue_init(&g_camera_system.message_queues[i], 
                              MESSAGE_QUEUE_SIZE) != 0) {
            LOG_ERROR("Failed to initialize message queue %d", i);
            return -1;
        }
    }
    
    // 初始化帧缓冲池
    if (frame_pool_init(&g_camera_system.frame_pool, FRAME_POOL_SIZE) != 0) {
        LOG_ERROR("Failed to initialize frame pool", 0);
        return -1;
    }
    
    g_camera_system.state = SYSTEM_IDLE;
    LOG_INFO("System initialization completed", 0);
    
    return 0;
}

/**
 * @brief 启动系统
 * @return 0成功，-1失败
 */
int system_start(void) {
    if (g_camera_system.state != SYSTEM_IDLE) {
        LOG_ERROR("System not in idle state, current state: %d", g_camera_system.state);
        return -1;
    }
    
    // 创建所有线程
    if (create_all_threads() != 0) {
        LOG_ERROR("Failed to create threads", 0);
        return -1;
    }
    
    // 等待所有线程启动
    int attempts = 0;
    while (atomic_load(&g_camera_system.sync.active_threads) < (MAX_THREADS - 1) && 
           attempts < 50) {
        usleep(100000); // 100ms
        attempts++;
    }
    
    if (atomic_load(&g_camera_system.sync.active_threads) < (MAX_THREADS - 1)) {
        LOG_ERROR("Not all threads started successfully. Active: %d, Expected: %d",
                 atomic_load(&g_camera_system.sync.active_threads), MAX_THREADS - 1);
        return -1;
    }
    
    LOG_INFO("All threads started successfully", 0);
    return 0;
}

/**
 * @brief 系统关闭
 */
void system_shutdown(void) {
    LOG_INFO("System shutdown initiated", 0);
    
    // 设置关闭标志
    atomic_store(&g_camera_system.sync.system_running, false);
    
    // 发送关闭消息给所有线程
    message_t shutdown_msg = {
        .type = MSG_SHUTDOWN,
        .timestamp = get_system_timestamp(),
        .source_thread = THREAD_MAIN,
        .dest_thread = THREAD_MAIN,
        .data_size = 0
    };
    
    for (int i = 1; i < MAX_THREADS; i++) {
        if (g_camera_system.threads[i].enabled) {
            shutdown_msg.dest_thread = i;
            message_queue_send(&g_camera_system.message_queues[i], &shutdown_msg);
        }
    }
    
    // 等待所有线程结束
    int timeout = 50; // 5秒超时
    while (atomic_load(&g_camera_system.sync.active_threads) > 0 && timeout > 0) {
        usleep(100000); // 100ms
        timeout--;
    }
    
    if (atomic_load(&g_camera_system.sync.active_threads) > 0) {
        LOG_WARN("Some threads did not exit gracefully", 0);
    }
    
    g_camera_system.state = SYSTEM_SHUTDOWN;
    LOG_INFO("System shutdown completed", 0);
}

/**
 * @brief 系统清理
 */
void system_cleanup(void) {
    LOG_INFO("System cleanup started", 0);
    
    // 销毁帧缓冲池
    frame_pool_destroy(&g_camera_system.frame_pool);
    
    // 销毁消息队列
    for (int i = 0; i < MAX_THREADS; i++) {
        message_queue_destroy(&g_camera_system.message_queues[i]);
    }
    
    // 销毁同步对象
    pthread_mutex_destroy(&g_camera_system.sync.config_mutex);
    pthread_mutex_destroy(&g_camera_system.sync.stats_mutex);
    pthread_mutex_destroy(&g_camera_system.sync.log_mutex);
    pthread_cond_destroy(&g_camera_system.sync.shutdown_cond);
    
    LOG_INFO("System cleanup completed", 0);
}

/**
 * @brief 创建所有线程
 * @return 0成功，-1失败
 */
int create_all_threads(void) {
    struct {
        thread_id_t id;
        void* (*func)(void*);
        int priority;
        int cpu_affinity;
    } thread_configs[] = {
        {THREAD_CAMERA,  camera_capture_thread,   90, 0},
        {THREAD_ENCODER, video_encoder_thread,    85, 1},
        {THREAD_AUDIO,   audio_capture_thread,    80, 2},
        {THREAD_STORAGE, storage_manager_thread,  50, 2},
        {THREAD_UI,      ui_manager_thread,       40, 3},
        {THREAD_MONITOR, system_monitor_thread,   20, 3},
        {THREAD_NETWORK, network_service_thread,  30, 3}
    };
    
    int num_threads = sizeof(thread_configs) / sizeof(thread_configs[0]);
    
    // 为每个线程分配独立的线程ID存储
    static thread_id_t thread_ids[MAX_THREADS];
    
    for (int i = 0; i < num_threads; i++) {
        thread_id_t tid = thread_configs[i].id;
        
        if (!g_camera_system.threads[tid].enabled) {
            continue;
        }
        
        // 将线程ID存储在静态数组中
        thread_ids[tid] = tid;
        
        printf("[DEBUG] Creating thread %d (%s) with tid pointer %p\n", 
               tid, g_camera_system.threads[tid].thread_name, (void*)&thread_ids[tid]);
        
        // 创建线程 - 传递静态数组中的地址
        int ret = pthread_create(&g_camera_system.threads[tid].thread_id,
                                NULL,
                                thread_configs[i].func,
                                &thread_ids[tid]); // 传递静态数组元素的地址
        
        if (ret != 0) {
            LOG_ERROR("Failed to create thread %s: %s", 
                     g_camera_system.threads[tid].thread_name, strerror(ret));
            return -1;
        }
        
        // 设置线程优先级
        set_thread_priority(g_camera_system.threads[tid].thread_id, 
                           thread_configs[i].priority);
        
        // 设置CPU亲和性
        set_thread_affinity(g_camera_system.threads[tid].thread_id, 
                           thread_configs[i].cpu_affinity);
        
        g_camera_system.threads[tid].status = THREAD_RUNNING;
        
        LOG_INFO("Thread %s created successfully", 
                g_camera_system.threads[tid].thread_name);
    }
    
    return 0;
}